package org.hyh.core.utils;

import com.alibaba.fastjson.JSON;
import org.hyh.core.model.entity.SysUser;
import org.hyh.core.model.vo.ResultVo;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * @auther :hyh
 * @desc :
 * @date :2020/7/12
 */
public class ResponseUtils {

    /**
     *  重置response 缓冲区的数据
     * @param response
     * @param data
     */
    public static void resetAndResponseToClient(HttpServletResponse response, Object data,boolean reset) {
        if (response.isCommitted()) {
            return;
        }
        if (reset) {
            response.resetBuffer();
        }

        response.setCharacterEncoding(StandardCharsets.UTF_8.displayName());
        response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            writer.write(JSON.toJSONString(data));
            response.flushBuffer();
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
            if (writer !=null) {
                writer.close();
            }
        }

    }

}
